package com.harisucici.websocketlib.im;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import com.harisucici.websocketlib.utils.Utils;

import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Map;

@Deprecated
public class HWebSocketClientService extends Service {
    public HWebSocketClient client;
    private HWebSocketClientBinder mBinder = new HWebSocketClientBinder();
    private final static int GRAY_SERVICE_ID = 1001;
    public final static String URL = "url";
    public final static String HEART = "heart";
    public final static int ON_OPEN = 1;
    public final static int ON_CLOSE = 0;
    public final static int ON_ERROR = 13;
    //锁屏唤醒
    private PowerManager.WakeLock wakeLock;
    private String url;
    private long heart;
    public final static String BROADCAST_ACTION = "com.im.harisucici";
    public final static String BROADCAST_ACTION_STATUS = "com.im.harisucici.status";
    public final static String WEBSOCKET_MSG = "message";
    public final static String WEBSOCKET_MSG_TYPE = "message_type";
    public final static String WEBSOCKET_STATUS = "status";
    public final static int WEB_CODE_OK = 200;
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            Log.i("HWebHeart", "检测websocket(心跳)");
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                }else{
                    Log.i("HWebHeart", "发送websocket(心跳)");
//                    send(String.valueOf(System.currentTimeMillis()));
                    send("心跳内容");
//                    client.sendPing();

                }
            } else {
                //如果client已为空，重新初始化连接
                client = null;
                initSocketClient();
            }
            //每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, heart);
        }
    };


    public HWebSocketClient getClient() {
        return client;
    }

    //灰色保活
//    public static class GrayInnerService extends Service {
//        @Override
//        public int onStartCommand(Intent intent, int flags, int startId) {
//            startForeground(GRAY_SERVICE_ID, new Notification());
//            stopForeground(true);
//            stopSelf();
//            return super.onStartCommand(intent, flags, startId);
//        }
//
//        @Override
//        public IBinder onBind(Intent intent) {
//            return null;
//        }
//    }


    //获取电源锁，保持服务在屏幕熄灭运行
    @SuppressLint("InvalidWakeLockTag")
    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }

    //Activity和service通讯
    public class HWebSocketClientBinder extends Binder {
        public HWebSocketClientService getService() {
            return HWebSocketClientService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //初始化websocket
        url = intent.getStringExtra(URL);
        //心跳时长
        heart = intent.getLongExtra(HEART, 10 * 1000);
        initSocketClient();
        //开启心跳检测
        mHandler.postDelayed(heartBeatRunnable, heart);

        //设置service为前台服务，提高优先级
//        if (Build.VERSION.SDK_INT < 18) {
//            //Android4.3以下 ，隐藏Notification上的图标
//            startForeground(GRAY_SERVICE_ID, new Notification());
//        } else if (Build.VERSION.SDK_INT > 18 && Build.VERSION.SDK_INT < 25) {
//            //Android4.3 - Android7.0，隐藏Notification上的图标
//            Intent innerIntent = new Intent(this, GrayInnerService.class);
//            startService(innerIntent);
//            startForeground(GRAY_SERVICE_ID, new Notification());
//        } else {
//            //Android7.0以上app启动后通知栏会出现一条"正在运行"的通知
//            startForeground(GRAY_SERVICE_ID, new Notification());
//        }

        acquireWakeLock();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        closeConnect();
        super.onDestroy();
    }

    // 初始化websocket连接
    private void initSocketClient() {
        URI uri = URI.create(url);
        client = new HWebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                super.onOpen(serverHandshake);
                Log.i("HWebSocketClientService", "网络状态：OPEN");
                Intent intent = new Intent();
                intent.setAction(BROADCAST_ACTION_STATUS);
                intent.putExtra(WEBSOCKET_STATUS, ON_OPEN);
                intent.putExtra(WEBSOCKET_MSG, "网络状态：OPEN");
                sendBroadcast(intent);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                super.onClose(code, reason, remote);
                Log.i("HWebSocketClientService", "网络状态：CLOSE");
                Intent intent = new Intent();
                intent.setAction(BROADCAST_ACTION_STATUS);
                intent.putExtra(WEBSOCKET_STATUS, code);
                intent.putExtra(WEBSOCKET_MSG, "网络状态：CLOSE");
                sendBroadcast(intent);
            }

            @Override
            public void onError(Exception ex) {
                super.onError(ex);
                Log.i("HWebSocketClientService", "网络状态：ERROR");
                Intent intent = new Intent();
                intent.setAction(BROADCAST_ACTION_STATUS);
                intent.putExtra(WEBSOCKET_STATUS, ON_ERROR);
                intent.putExtra(WEBSOCKET_MSG, "网络状态：ERROR");
                sendBroadcast(intent);
            }

            @Override
            public void onMessage(String message) {
                Log.i("HWebSocketClientService", "收到的消息：" + message);
                Map<String, String> map = Utils.getInstance().jso2map(message);
                if (map == null) {
                    return;
                }
                int code = Integer.parseInt(map.get("code"));
                // 收到的消息：{"cmdType":"P2P","code":1000,"msg":"不支持的消息类型"}
                if (code == WEB_CODE_OK) {
                    Intent intent = new Intent();
                    intent.setAction(BROADCAST_ACTION);
                    intent.putExtra(WEBSOCKET_MSG_TYPE, map.get("cmdType"));
                    intent.putExtra(WEBSOCKET_MSG, map.get("payLoad"));
                    sendBroadcast(intent);
                    checkLockAndShowNotification(message);
                } else {
                    //错误信息
                    Intent intent = new Intent();
                    intent.setAction(BROADCAST_ACTION_STATUS);
                    intent.putExtra(WEBSOCKET_STATUS, code);
                    intent.putExtra(WEBSOCKET_MSG, map.get("msg"));
                    sendBroadcast(intent);
                }


            }


        };
        client.setConnectionLostTimeout(0);//超时时间

        connect();
    }

    //开始连接
    private void connect() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    // 发送消息
    public void send(String msg) {
        if (client == null) {
            return;
        }

        // 连上
        if (client.isOpen()) {
            Log.i("HWebSocketClientService", "发出的消息：" + msg);
            client.send(msg);
        } else {
            //没连上 重连
//            connect();
            if (client.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)) {
                try {
                    client.connect();
                } catch (IllegalStateException e) {
                }
            } else if (client.getReadyState().equals(ReadyState.CLOSING) || client.getReadyState().equals(ReadyState.CLOSED)) {
                client.reconnect();
            }
        }
    }

    // 断开连接
    public void closeConnect() {
        try {
            if (null != client) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }


    // 检查锁屏状态，如果锁屏先点亮屏幕
    private void checkLockAndShowNotification(String content) {
        //管理锁屏的一个服务
        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        //锁屏
        if (km.inKeyguardRestrictedInputMode()) {
            //获取电源管理器对象
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            if (!pm.isScreenOn()) {
                @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                        PowerManager.PARTIAL_WAKE_LOCK, "bright");
                //点亮屏幕
                wl.acquire();
                //任务结束后释放
                wl.release();
            }
//            sendNotification(content);
        } else {
//            sendNotification(content);
        }
    }

    //发送通知
//    private void sendNotification(String content) {
//       Intent intent = new Intent();
//        intent.setClass(this, MainActivity.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        Notification notification = new NotificationCompat.Builder(this)
//                .setAutoCancel(true)
//                // 设置该通知优先级
//                .setPriority(Notification.PRIORITY_MAX)
//                .setSmallIcon(R.drawable.icon)
//                .setContentTitle("服务器")
//                .setContentText(content)
//                .setVisibility(VISIBILITY_PUBLIC)
//                .setWhen(System.currentTimeMillis())
//                // 向通知添加声音、闪灯和振动效果
//                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
//                .setContentIntent(pendingIntent)
//                .build();
//        notifyManager.notify(1, notification);//id要保证唯一
//    }

    // 开启重连
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.i("HWebSocketClientService", "开始重连");
                    client.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

